/*
* File: httptTools.js
* Version: 1.1.0
* Author: zengdada
* Copyright 2017
* http://www.zengdada.cn
*/

/***
 *  发起请求 （不依赖JQ 可单独使用）
 * @param url 请求地址
 * @param params 参数
 * @param successFunc 成功回掉
 * @param errorFunc 失败回掉
 * @param completeFunc 完成回掉
 * @param otherConfigure 其他参数（遵循JQ ajax参数规则(没有JQ时不够完善)）
 */
var ajaxRequest = function (url, params, successFunc, errorFunc1, completeFunc,
                            otherConfigure) {
    var isJQ = window.jQuery !== undefined,
        errorFunc = function (data) {
            if (data.status === 500 || data.code === undefined) {
                console.log(data);
                my_alert("服务器错误请稍后再试");
                errorFunc1 && errorFunc1(data);
                return
            }
            data.code === 1024 ? my_alert(data.code + '：请登录后再试！！') : errorFunc1 ? errorFunc1(data) : my_alert(data.code + '：' + data.message);
        },
        my_alert = function (msg) {
            !window.layer ? alert(msg) : layer.open({
                title: '出错了哦'
                , tipsMore: true
                , content: msg
            });
        }, successFunc = successFunc || function (e) {
        }, completeFunc = completeFunc || function (e) {
        };
    var ajax_params = {
        url: url,
        method: 'POST',
        dataType: 'JSON',
        data: params,
        success: function (data) {
            data.success ? successFunc(data) : errorFunc(data);
        },
        error: errorFunc,
        complete: completeFunc
    };
    if (otherConfigure !== undefined && otherConfigure != null)
        ajax_params = isJQ ? $.extend(ajax_params, otherConfigure) : extend(ajax_params, otherConfigure)
    isJQ ? $.ajax(ajax_params) : ajax(ajax_params);
};

var ajaxRequestByCsrf = function (url, params, successFunc, errorFunc, completeFunc,
                                  otherConfigure) {
    var token, header;
    try {
        token = document.querySelector('meta[name="_csrf"]').getAttribute('content');
        header = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');
    } catch (e) {
        console.log(e);
        console.log("没有找到_csrf/_csrf_header");
    }
    var otherConfigure = otherConfigure || {};
    if (token && header) {
        otherConfigure.headers = {};
        otherConfigure.headers[header] = token;
    }
    ajaxRequest(url, params, successFunc, errorFunc, completeFunc,
        otherConfigure);
};

function extend(a, b) {
    for (var key in b) {
        a[key] = b[key];
    }
    return a;
}

function ajax() {
    var ajaxData = {
        method: (arguments[0].method || "GET").toUpperCase(),
        url: arguments[0].url || "",
        async: arguments[0].async || "true",
        data: arguments[0].data || null,
        dataType: (arguments[0].dataType || "text").toLowerCase(),
        contentType: arguments[0].contentType || "application/x-www-form-urlencoded",
        headers: arguments[0].headers || {},
        beforeSend: arguments[0].beforeSend || function () {
        },
        success: arguments[0].success || function () {
        },
        error: arguments[0].error || function () {
        },
        complete: arguments[0].complete || function () {
        }
    };
    ajaxData.beforeSend();
    var xhr;
    if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    } else if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        alert("浏览器不支持！");
        return;
    }
    xhr.responseType = ajaxData.dataType;
    ajaxData.url = ajaxData.method === 'GET' ? ajaxData.url.indexOf('?') > 0 ? ajaxData.url + '&' + convertData(ajaxData.data) : ajaxData.url + '?' + convertData(ajaxData.data) : ajaxData.url;
    xhr.open(ajaxData.method, ajaxData.url, ajaxData.async);
    for (key in ajaxData.headers) {
        xhr.setRequestHeader(key, ajaxData.headers[key]);
    }
    xhr.setRequestHeader("Content-Type", ajaxData.contentType);
    ajaxData.method === 'GET' ? xhr.send() : xhr.send(convertData(ajaxData.data));
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            ajaxData.complete();
            xhr.status === 200 ? ajaxData.success(xhr.response) : ajaxData.error(xhr.status + ':' + xhr.statusText)
        }
    }
}


function convertData(data) {
    if (typeof data === 'object') {
        var convertResult = "";
        for (var c in data) {
            convertResult += c + "=" + data[c] + "&";
        }
        convertResult = convertResult.substring(0, convertResult.length - 1)
        return convertResult;
    } else {
        return data;
    }
}

/**
 * 使用POST请求下载文件
 * @param url
 * @param params
 */
function downloadFileByPost(url, params) {
    var form = $('body form.post-download-file-temp-form');
    if (form.length === 0) form = $('<form class="post-download-file-temp-form" method="POST" action="' + url + '">');
    form.empty();
    form.append($('<input type="hidden" name="_csrf" value="' + document.querySelector('meta[name="_csrf"]').getAttribute('content') + '">'));
    $.each(params, function (k, v) {
        form.append($('<input type="hidden" name="' + k + '" value="' + v + '">'));
    });
    $('body').append(form);
    form.submit();
}